package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQuery;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.util.PageHelperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private ITravelCommentService travelCommentService;



    @Override
    public void save(TravelComment travelComment) {

        //获取关联第二层评论的id
        String refId = travelComment.getRefComment().getId();
        //判断该id是否为空
        if (StringUtils.hasLength(refId)){
            //获取ref的对象
            TravelComment comment = travelCommentService.get(refId);
            //把关联的评论设置进去
            travelComment.setRefComment(comment);
        }

        //如果id为 "" ,spring-data-mongodb 不会自动生成id注入
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());
        repository.save(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {

        repository.save(travelComment);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }


    @Override
    public List<TravelComment> list() {


        return repository.findAll();
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {

        //查询封装类
        Query query = new Query();
        //分页数据 , currentPage , pageSite


        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");




        //后台游记管理,查询出author作者的数据
        Page<TravelComment> page = PageHelperUtil.query(template, pageable, TravelComment.class, query, qo);


        //list Pageable total 封装三个数据,返回给页面
        return page;
    }

    @Override
    public List<TravelComment> queryByTravelId(String travelId) {

        List<TravelComment> list = repository.findByTravelId(travelId);
        return list;
    }


}
